﻿using Alipay.AopSdk.Core.Domain;
using Microsoft.AspNet.SignalR.Hosting;
using Microsoft.EntityFrameworkCore;
using SmartWMS.Common.Extensions;
using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.BasicsDatum;
using SmartWMS.Domain.BusinessManage;
using SmartWMS.Domain.FinanceManage;
using SmartWMS.Domain.StatementManage;
using SmartWMS.EntityFramework;
using SmartWMS.Server.BusinessServer.SalesReturnServer.Dto;
using SmartWMS.Server.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartWMS.Server.BusinessServer.SalesReturnServer
{
    public class SalesReturnServers: ISalesReturnServers
    {


        private readonly IRepository<SalesReturn> _salesReturn;

        private readonly IRepository<SalesManagement> _salesManagement;
        private readonly IRepository<SmartWMS.Domain.BasicsDatum.Product> _product;
        private readonly IRepository<Custom> _custon;
        private readonly SmartWMSContext _SmartWMSContext;
        private readonly IRepository<Payment> _payment;

        public SalesReturnServers(IRepository<SalesReturn> salesReturn, IRepository<SalesManagement> _salesManagement, IRepository<SmartWMS.Domain.BasicsDatum.Product> _product, IRepository<Custom> custon, SmartWMSContext SmartWMSContext, IRepository<Payment> payment)
        {
            _salesReturn = salesReturn;
            this._salesManagement = _salesManagement;
            this._product = _product;
            _custon = custon;
            _SmartWMSContext= SmartWMSContext;
            _payment = payment;
        }

        /// <summary>
        /// 显示销售退货
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<SalesReturnDtoPes>>> GetSalesReturnDtoPes(SalesReturnPage dto)
        {
            try
            {
                var salesreturnlist = _salesReturn.GetListQuery();
                var salesManagementlist= _salesManagement.GetListQuery();
                var productlist = _product.GetListQuery();
                //var customlist = _custon.GetListQuery();
                var list = (from a in salesreturnlist
                              join c in productlist on a.ProductId equals c.ProductCode
                              select new SalesReturnDtoPes
                              {
                                  Id = a.Id,
                                  SalesId = a.SalesId,
                                  SalesReturnCode = a.SalesReturnCode,
                                  ProductId = a.ProductId,
                                  Unit = c.Unit,
                                  Price = c.Price,
                                  ProductName = c.ProductName,
                                  Specs = c.Specs,
                                  SalesReturnNumber = a.SalesReturnNumber,
                                  SalesReturnSum = a.SalesReturnSum,
                                  ClientName = a.ClientName,
                                  IntState = a.State.ToString(),
                                  IntState2 = a.State.ToString(),
                                  SalesReturnState = a.SalesReturnState,
                                  CreateTime = a.CreateTime,
                              }).ToList();
                if (!string.IsNullOrEmpty(dto.SalesReturnCode)) {
                    list= list.Where(x => x.SalesReturnCode.Contains(dto.SalesReturnCode)).ToList();
                }
                if (!string.IsNullOrEmpty(dto.ProductName))
                {
                    list = list.Where(x => x.ProductName.Contains(dto.ProductName)).ToList();
                }
                if (!string.IsNullOrEmpty(dto.SalesId))
                {
                    list = list.Where(x => x.SalesId.Contains(dto.SalesId)).ToList();
                }
                int totalCount = list.Count();
                int pageCount = (int)Math.Ceiling(totalCount * 1.0 / dto.size);
                list = list.Skip((dto.page - 1) * dto.size).Take(dto.size).ToList();
                return new Response<List<SalesReturnDtoPes>> { Data = list, TotalCount = totalCount, PageCount = pageCount };
                
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 查看详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public  List<SalesReturnDtoPes> GetSalesReturnShow(SalesReturnDtoPes dto) {
            try
            {
                //销售退货表单
                var salesreturnlist = _salesReturn.GetListQuery();
                //销售表单
                var salesManagementlist = _salesManagement.GetListQuery();
                //产品表单
                var productlist = _product.GetListQuery();
                //客户表单
                var customlist = _custon.GetListQuery();
                var list = (from a in salesreturnlist
                            join b in salesManagementlist on a.SalesId equals b.SalesCode
                            join c in productlist on a.ProductId equals c.ProductCode 
                            join d in customlist on b.ClientCode equals d.CustomrCode
                            where a.Id==dto.Id
                            select new SalesReturnDtoPes
                            {
                                Id = a.Id,
                                SalesId = a.SalesId,
                                SalesReturnCode = a.SalesReturnCode,
                                ProductId = a.ProductId,
                                Unit = c.Unit,
                                Price = c.Price,
                                CustomrCode = d.CustomrCode,
                                Phones = d.Phone,
                                ProductName = c.ProductName,
                                Specs = c.Specs,
                                SalesReturnNumber = a.SalesReturnNumber,
                                SalesReturnSum = a.SalesReturnSum,
                                ClientName = b.ClientName,
                                IntState = a.State.ToString(),
                                IntState2 = a.State.ToString(),
                                SalesReturnState = a.SalesReturnState,
                                CreateTime = a.CreateTime,
                                Inventory= c.Inventory,
                                DocumentType= b.DocumentType,
                               Creator= b.Creator,
                                Comment = d.Comment,
                            }).ToList();
                return list;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改状态（确认订单）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdateStateSalesReturn(PaymentDtoPes dto) {
            try
            {
                //查询退货表单是否存在
                var list = _salesReturn.GetListQuery().FirstOrDefault(t => t.SalesReturnCode == dto.SalesReturnCode);
                //如果存在
                if (list != null)
                {
                    //修改状态
                    list.State = 2;
                    
                    //修改退货状态
                    using (var tran = _SmartWMSContext.Database.BeginTransaction())
                    {
                        try
                        {

                            var result = await _salesReturn.UpdateAsync(list);
                            //如果修改成功
                            if (result > 0) { 
                                //添加支付表单
                            var plist= await _payment.InsertAsync(dto.MapTo<Payment>());
                                if (plist > 0)
                                {
                                    // 完成事务
                                tran.Commit();
                                return Response<bool>.Ok(true);
                                 }
                            else
                                {
                                    //回滚
                                tran.Rollback();
                                return Response<bool>.Fail(false);
                            }
                            }
                            else
                            {
                                //回滚
                                tran.Rollback();
                                return Response<bool>.Fail(false);
                            } 
                          
                        }
                        catch (Exception)
                        {
                            // 处理异常
                            tran.Rollback();
                            return Response<bool>.Fail(false);
                          
                        }

                    }


                }
                else {
                    return  Response<bool>.Fail(false);
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 驳回订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdaSalesReturn(SalesReturnDtoPes dto) {
            try
            {
                var list= await  _salesReturn.GetListQuery().FirstOrDefaultAsync(t => t.SalesReturnCode == dto.SalesReturnCode);
                if (list != null) {
                    list.State = 3;
                    var result = await _salesReturn.UpdateAsync(list);
                    if (result > 0)
                    {
                        return Response<bool>.Ok(true);
                    }
                    else
                    {
                        return Response<bool>.Fail(false);
                    }
                }else
                {
                    return Response<bool>.Fail(false);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 付款方式
        /// </summary>
        /// <returns></returns>
        public  Task<Response<List<PayType>>> GetPayType() {
            try
            {
                var list=  _SmartWMSContext.PayType.ToList();
                return Task.FromResult(Response<List<PayType>>.Ok(list));
            }
            catch (Exception)
            {

                throw;
            }
        }




    }
}
